package com.sky.controller.admin;

import com.sky.annotation.AutoFill;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
public class DishController {


    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 页面分页查询
     */
    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("分页查询:{}", dishPageQueryDTO);
        PageResult page = dishService.page(dishPageQueryDTO);
        return Result.success(page);
    }

    /*新增菜品*/
    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品，菜品数据：{}", dishDTO);
        //清空当前分类redis中的缓存
        removeCache("*dish_" + dishDTO.getCategoryId());
        dishService.save(dishDTO);
        return Result.success();

    }

    /*删除菜品*/
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids) {
        log.info("删除菜品，id为：{}", ids);
        dishService.delete(ids);
        //清空redis中的缓存
        removeCache("*dish_*");
        return Result.success();
    }
    /*修改菜品*/
    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品，菜品数据：{}", dishDTO);
        //清空redis中的缓存
        removeCache("*dish_*");
        dishService.update(dishDTO);
        return Result.success();
    }

    /*根据id查询菜品*/
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id) {
        log.info("查询菜品，id为：{}", id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }
    /*根据分类id查询菜品*/
    @GetMapping("/list")
    public Result<List<DishVO>> list(@RequestParam Long categoryId) {
        log.info("查询菜品");
        List<DishVO> dishVOList = dishService.list(categoryId);
        return Result.success(dishVOList);
    }

    /*菜品停售与起售*/
    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status, Long id) {
        log.info("起售或停售菜品，id：{}", id);
        dishService.startOrStop(status, id);
        removeCache("*dish_*");
        return Result.success();
    }

    private void removeCache(String  key) {
        //清空redis中的缓存
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }

}
